package com.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TwoArrayIntersect.. 查找两个数组相交部分
 *
 * @author Lizhong
 * @date 2019/8/28
 */
public class TwoArrayIntersect {

    public int[] intersect(int[] nums1, int[] nums2) {

        Map<Integer, Integer> set = new HashMap<>(nums1.length);
        for (int num : nums1) {
            Integer count = set.get(num);
            count = count == null ? 1 : ++count;
            set.put(num, count);
        }


        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < nums2.length; i++) {
            int num = nums2[i];
            Integer x = set.get(num);
            if (x != null) {
                if (x >= 1) {
                    list.add(num);
                    set.put(num, --x);
                }
            }

        }


        int[] r = new int[list.size()];
        int j = 0;
        for (Integer integer : list) {
            r[j++] = integer;
        }

        return r;
    }

    public int[] intersect02(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i = 0;
        int j = 0;
        List<Integer> integers = new ArrayList<>();
        while (i < nums1.length && j < nums2.length) {
            int i1 = nums1[i];
            int j1 = nums2[j];

            if (j1 == i1) {
                integers.add(i1);
                j++;
                i++;
            } else if (i1 > j1) {
                j++;
            } else {
                i++;
            }
        }
        int r[] = new int[integers.size()];
        for (int k = 0; k < integers.size(); k++) {
            r[k] = integers.get(k);
        }
        return r;
    }
}
